<template>
  <div style="width:98%;margin-left:1%;margin-top:2%;display:block">
    <a-table bordered :dataSource="dataSource" :columns="columns"  :scroll="{ x:2650,y:532 }">
      <template slot="orderId" slot-scope="text, record">
        <editable-cell
                :ref="`orderId_${record.key}`"
                :autoSave=true
                :required="true"
                :decoratorOptions="rules.orderId"
                placeholder='请输入'
                :value="text"
                :text="text"
                />
      </template>
      <template slot="username" slot-scope="text, record">
        <editable-cell
                :ref="`username_${record.key}`"
                :autoSave=true
                :required="true"
                :decoratorOptions="rules.username"
                placeholder='请输入'
                :value="text"
                :text="text"
               />
      </template>
      <template slot="orderDate" slot-scope="text, record">
        <editable-cell
                :ref="`orderDate_${record.key}`"
                :autoSave=true
                :required="true"
                :decoratorOptions="rules.orderDate"
                placeholder='请输入'
                :value="text"
                :text="text"/>
      </template>
      <template slot="shipAddress1" slot-scope="text, record">
        <editable-cell
                :ref="`shipAddress1_${record.key}`"
                :defaultEditable="record.editable"
                :autoSave=true
                :required="true"
                :decoratorOptions="rules.shipAddress1"
                placeholder='请输入'
                :value="text"
                :text="text"
                @valueChange="onCellChange(record.key, 'shipAddress1', $event)"/>
      </template>
      <template slot="shipCity" slot-scope="text, record">
        <editable-cell
                :ref="`shipCity_${record.key}`"
                :defaultEditable="record.editable"
                :autoSave=true
                :required="true"
                :decoratorOptions="rules.shipCity"
                placeholder='请输入'
                :value="text"
                :text="text"
                @valueChange="onCellChange(record.key, 'shipCity', $event)"/>
      </template>
      <template slot="shipState" slot-scope="text, record">
        <editable-cell
                :ref="`shipState_${record.key}`"
                :defaultEditable="record.editable"
                :autoSave=true
                :required="true"
                :decoratorOptions="rules.shipState"
                placeholder='请输入'
                :value="text"
                :text="text"
                @valueChange="onCellChange(record.key, 'shipState', $event)"/>
      </template>
      <template slot="shipZip" slot-scope="text, record">
        <editable-cell
                :ref="`shipZip_${record.key}`"
                :defaultEditable="record.editable"
                :autoSave=true
                :required="true"
                :decoratorOptions="rules.shipZip"
                placeholder='请输入'
                :value="text"
                :text="text"
                @valueChange="onCellChange(record.key, 'shipZip', $event)"/>
      </template>
      <template slot="shipCountry" slot-scope="text, record">
        <editable-cell
                :ref="`shipCountry_${record.key}`"
                :defaultEditable="record.editable"
                :autoSave=true
                :required="true"
                :decoratorOptions="rules.shipCountry"
                placeholder='请输入'
                :value="text"
                :text="text"
                @valueChange="onCellChange(record.key, 'shipCountry', $event)"/>
      </template>
      <template slot="courier" slot-scope="text, record">
        <editable-cell
                :ref="`courier_${record.key}`"
                :defaultEditable="record.editable"
                :autoSave=true
                :required="true"
                :decoratorOptions="rules.courier"
                placeholder='请输入'
                :value="text"
                :text="text"
                @valueChange="onCellChange(record.key, 'courier', $event)"/>
      </template>
      <template slot="totalPrice" slot-scope="text, record">
        <editable-cell
                :ref="`totalPrice_${record.key}`"
                :defaultEditable="record.editable"
                :autoSave=true
                :required="true"
                :decoratorOptions="rules.totalPrice"
                placeholder='请输入'
                :value="text"
                :text="text"
                @valueChange="onCellChange(record.key, 'totalPrice', $event)"/>
      </template>
      <template slot="shipToLastName" slot-scope="text, record">
        <editable-cell
                :ref="`shipToLastName_${record.key}`"
                :defaultEditable="record.editable"
                :autoSave=true
                :required="true"
                :decoratorOptions="rules.shipToLastName"
                placeholder='请输入'
                :value="text"
                :text="text"
                @valueChange="onCellChange(record.key, 'shipToLastName', $event)"/>
      </template>
      <template slot="creditCard" slot-scope="text, record">
        <editable-cell
                :ref="`creditCard_${record.key}`"
                :autoSave=true
                :required="true"
                :decoratorOptions="rules.creditCard"
                placeholder='请输入'
                :value="text"
                :text="text"/>
      </template>
      <template slot="cardType" slot-scope="text, record">
        <editable-cell
                :ref="`cardType_${record.key}`"
                :autoSave=true
                :required="true"
                :decoratorOptions="rules.cardType"
                placeholder='请输入'
                :value="text"
                :text="text"
              />
      </template>
      <template slot="locale" slot-scope="text, record">
        <editable-cell
                :ref="`locale_${record.key}`"
                :autoSave=true
                :required="true"
                :decoratorOptions="rules.locale"
                placeholder='请输入'
                :value="text"
                :text="text"
                />
      </template>

      <template slot="operation" slot-scope="text, record">
        <div class='editable-row-operations'>

          <span v-if="record.editable">
            <a @click="() => save(record.key)">确定</a>
              <a-divider type="vertical" />
            <a-popconfirm title='确定取消吗?' @confirm="() => cancel(record.key)">
              <a>取消</a>
              <a-divider type="vertical" />
            </a-popconfirm>
          </span>
          <span v-else>
            <a @click="() => edit(record.key)">修改</a>
              <a-divider type="vertical" />
            <a @click="() => onSend(record.key)" :visibility="visible">发货</a>
              <a-divider type="vertical" />
          </span>
          <a-popconfirm v-if="dataSource.length" title="确定退单吗?" @confirm="() => onDelete(record.key)">
            <span>
              <a href="javascript:;">退单</a>
            </span>
          </a-popconfirm>

        </div>
      </template>

    </a-table>
  </div>
</template>
<script>
  import EditableCell from '@/components/cell.vue';
  import moment from 'moment';
import { mapActions , mapState} from 'vuex'
  /*
  * EditableCell Code https://github.com/vueComponent/ant-design-vue/blob/master/components/table/demo/EditableCell.vue
  */
  export default {
    components: {
      EditableCell,
    },
  computed: {
    ...mapState({
      signIn: state => state.account.signIn,
      account: state => state.account.account
    })
  },
    data() {
      return {
        visible: true,
        signData: [],
        mulData: [],
        dateFormat: 'YYYY-MM-DD',
        dataSource: [
        ],
        count: 0,
        columns: [
          {
            title: '订单账号',
            dataIndex: 'orderId',
            width: '150',
            scopedSlots: { customRender: 'orderId' },
          },
          {
            title: '用户账号',
            dataIndex: 'username',
            width: '150',
            scopedSlots: { customRender: 'username' },
          },
          {
            title: '下单时间',
            dataIndex: 'orderDate',
            width: '150',
            scopedSlots: { customRender: 'orderDate' },
          },
          {
            title: '收货地址',
            dataIndex: 'shipAddress1',
            width: '150',
            scopedSlots: { customRender: 'shipAddress1' },
          },
          {
            title: '收货城市',
            dataIndex: 'shipCity',
            width: '150',
            scopedSlots: { customRender: 'shipCity' },
          },
          {
            title: '收货州',
            dataIndex: 'shipState',
            width: '150',
            scopedSlots: { customRender: 'shipState' },
          },
          {
            title: '收货邮编',
            dataIndex: 'shipZip',
            width: '50',
            scopedSlots: { customRender: 'shipZip' },
          },
          {
            title: '收货国家',
            dataIndex: 'shipCountry',
            width: '150',
            scopedSlots: { customRender: 'shipCountry' },
          },
          {
            title: '快递公司',
            dataIndex: 'courier',
            width: '50',
            scopedSlots: { customRender: 'courier' },
          },
          {
            title: '订单总额',
            dataIndex: 'totalPrice',
            width: '150',
            scopedSlots: { customRender: 'totalPrice' },
          },
          {
            title: '用户姓氏',
            dataIndex: 'shipToLastName',
            width: '150',
            scopedSlots: { customRender: 'shipToLastName' },
          },
          {
            title: '支付卡号',
            dataIndex: 'creditCard',
            width: '150',
            scopedSlots: { customRender: 'creditCard'},
          },
          {
            title: '支付类型',
            dataIndex: 'cardType',
            width: '30',
            scopedSlots: { customRender: 'cardType' },
          },
          {
            title: '发货地址',
            dataIndex: 'locale',
            width: '150',
            scopedSlots: { customRender: 'locale' },
          },
          {
            title: '操作',
            dataIndex: 'operation',
            width: '200',
            scopedSlots: { customRender: 'operation' },
            fixed: 'right',
          },
        ],
        fields:['orderId','username','orderDate','shipAddress1','shipCity','shipState','shipZip','shipCountry','courier','totalPrice','shipToLastName','creditCard','cardType','locale'],
       rules: {
         orderId: {
            rules: [{
              required: true,
            }],
          },
          username: {
            rules: [{
              required: true,
            }],
          },
         orderDate: {
            rules: [{
              required: true,
            }],
          },
          shipAddress1: {
            rules: [{
              required: true,
              message: '请输入收货地址',
            }],
          },
          shipCity: {
            rules: [{
              required: true,
              message: '请输入收货城市',
            },
            {
              message: '最长支持25位',
              max: 25,
            }],
          },
          shipState: {
            rules: [{
              required: true,
              message: '请输入收货州',
            }],
          },
          shipZip: {
            rules: [{
              required: true,
              message: '请输入收货邮编',
            }],
          },
          shipCountry: {
            rules: [{
              required: true,
              message: '请输入收货国家',
            }],
          },
          courier: {
            rules: [{
              required: true,
              message: '请输入快递公司',
            }],
          },
          totalPrice: {
            rules: [{
              required: true,
              message: '请输入价格',
            }],
          },
          shipToLastName: {
            rules: [{
              required: true,
              message: '请输入收货者姓氏',
            }],
          },
          creditCard: {
            rules: [{
              required: true,
            }],
          },
          cardType: {
            rules: [{
              required: true,
            }],
          },
          locale: {
            rules: [{
              required: true,
            }],
          },
        // emailList:[],
       }
      };
    },
    methods: {
      ...mapActions({
      getOrderList: 'order/getOrderList',
      updateOrder: 'order/updateOrder',
      }),
      moment,
      // 模糊搜索
      handleSearch(value) {
        let result;
        if (!value || value.indexOf('@') >= 0) {
          result = [];
        } else {
          result = ['gmail.com', '163.com', 'qq.com'].map(domain => `${value}@${domain}`);
        }
        this.emailList = result
      },
      // input Change事件
      onCellChange(key, dataIndex, value) {
        // console.log(`${dataIndex}：${value} `);
        const dataSource = [...this.dataSource];
        const target = dataSource.find(item => item.key === key);
        if (target) {
            target[dataIndex] = value;
          this.dataSource = dataSource;
        }
      },
      // 删除
      onDelete(key) {
        // 拷贝数组数据
        const dataSource = [...this.dataSource];
        // 过滤移除当前项目
        this.dataSource = dataSource.filter(item => item.key !== key);
        let updateD = dataSource[key]
        this.updateOrderStatus({orderId:updateD.orderId,status:'R'}).then((res)=>{
          this.openNotification("OK","退单成功",res)
          this.count--
        },(error)=>{
          this.openNotification("NOK","退单失败",error)
        })
      },
      onSend(key){
        const dataSource = [...this.dataSource];
        // 过滤移除当前项目
        this.dataSource = dataSource.filter(item => item.key !== key);
        let updateD = dataSource[key]
        this.updateOrderStatus({orderId:updateD.orderId,status:'E'}).then((res)=>{
          this.openNotification("OK","发货成功",res)
          this.count--
        },(error)=>{
          this.openNotification("NOK","发货失败",error)
        })
      },
      // 点击编辑
      edit(key) {
        const newData = [...this.dataSource];
        const target = newData.filter(item => key === item.key)[0];
        if (target) {
          target.editable = true;
          this.dataSource = newData;
        }
        this.visible = false;
      },
      // 点击保存
      save(key) {
        this.validateRow(key, this.fields, (err, values) => {
          if (!err) {
            const newData = [...this.dataSource];
            const row = newData.find(item => key === item.key);
            if (row) {
              // 用户数据合并到原对象上
              Object.assign(row, values);
              delete row.editable;
              this.signData = row;
              // console.log('单行保存row', row);
              // target 保存了最新行数据，可以提价到后台
              this.dataSource = newData;

              let updateD = this.dataSource[key]
              this.updateOrder(updateD).then((res)=>{
                this.openNotification("OK","更新订单成功",res)
              },(error)=>{
                this.openNotification("NOK","更新订单失败",error)
              })
            }
          }
        });
        this.visible = true
      },
      // 点击取消
      cancel(key) {
        const newData = [...this.dataSource];
        const target = newData.filter(item => key === item.key)[0];
        if (target) {
          delete target.editable;
          this.dataSource = newData;
        }
        this.visible = true
      },
      // validateRow可以提取为公共函数
      validateRow(key, fields, callback) {
        // 查找验证是否通过
        const row = {};
        let err = false;
        // forEach 对每一个验证，可以更改为some满足一个就提醒
        fields.forEach(filed => {
          let refName = `${filed}_${key}`;
          let result = this.$refs[refName].validate();
          row[filed] = result.value;
          if (!result.success) {
            err = true;
          }
        });
        callback(err, row);
      },
      // 批量提交保存数据
      handleSave() {
        const newData = [...this.dataSource];
        // 找出处于可编辑行
        const rows = newData.filter(row => {
          return row.editable;
        });
        // 一个个校验行
        rows.forEach(row => {
          this.validateRow(row.key, this.fields, (err, values) => {
            if (!err) {
              // 行记录数据合并到row中
              Object.assign(row, values);
              count++;
            }
          });
        });
        // 最终数据在rows中;
        if (rows.length === count) {
          // 数据在rows,提交数据
          this.mulData = rows;
          // console.log('批量多行rows', rows);
        }
      },
      openNotification(type,title,msg) {
      let iconType = ''
      let iconColor = ''
      if(type=='OK'){
        iconType = 'smile'
        iconColor = '#52c41a'
      }
      else
      {
        iconType = 'frown'
        iconColor = '#eb2f96'
      }
      this.$notification.open({
        message: title,
        description: msg,
        icon: h => h('a-icon', {
          props: {
            type: iconType,
            theme: 'twoTone',
            'two-tone-color': iconColor
          }
        }),

      });
    }
      // 点击提交
    },
    mounted(){
      if(this.signIn===false||this.account===null){
        this.openNotification("NOK","未登录","请先登录管理员账号!")
        this.$router.push("/mainPage/login")
      }
      else{
        this.getOrderList().then((res)=>{
          console.log(res)
          let i = 0
          for(let item of res){
            item.key = i++
            this.dataSource.push(item);
          }
          this.count = this.dataSource.length
          this.openNotification("OK","更新订单列表成功","订单列表已更新!")
        }, (error) => {
          this.openNotification("NOK","更新订单列表失败",error)
        })
      }
    }

  };
</script>
<style scoped>
  .editable-row-operations a {
    margin-right: 8px;
  }
  li {
    text-align: left;
  }
  pre {
    padding: 10px;
    background-color: rgba(0, 0, 0, 0.65);
    color: #ccc;
  }
</style>
